{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import mxnet as mx\n",
    "from mxnet import init, gluon, nd, autograd, image\n",
    "from mxnet.gluon.data import vision\n",
    "from mxnet.gluon.model_zoo import vision as models\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tqdm import tqdm\n",
    "import cv2\n",
    "import h5py\n",
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "\n",
    "ctx = mx.gpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def transform1(data, label):\n",
    "    data = data.astype('float32') / 255\n",
    "    pre_224 = [image.ForceResizeAug((224,224)), image.ColorNormalizeAug(\n",
    "        mean=nd.array([0.485, 0.456, 0.406]), std=nd.array([0.229, 0.224, 0.225]))]\n",
    "    for pre in pre_224:\n",
    "        data = pre(data)\n",
    "    data = nd.transpose(data, (2,0,1))\n",
    "    return data, nd.array([label]).asscalar().astype('float32')\n",
    "\n",
    "def transform2(data, label):\n",
    "    data = data.astype('float32') / 255\n",
    "    pre_299 = [image.ForceResizeAug((299,299)), image.ColorNormalizeAug(\n",
    "        mean=nd.array([0.485, 0.456, 0.406]), std=nd.array([0.229, 0.224, 0.225]))]\n",
    "    for pre in pre_299:\n",
    "        data = pre(data)\n",
    "    data = nd.transpose(data, (2,0,1))\n",
    "    return data, nd.array([label]).asscalar().astype('float32')\n",
    "\n",
    "def save_features(model_name, data_iter, ignore=False):\n",
    "    if os.path.exists('features_test_%s.nd' % model_name):\n",
    "        return\n",
    "    net = models.get_model(model_name, pretrained=True, ctx=ctx)\n",
    "    features = []\n",
    "    for data, _ in tqdm(data_iter):\n",
    "        feature = net.features(data.as_in_context(mx.gpu()))\n",
    "        feature = gluon.nn.Flatten()(feature)\n",
    "        features.append(feature.as_in_context(mx.cpu()))\n",
    "        nd.waitall()\n",
    "    features = nd.concat(*features, dim=0)\n",
    "    nd.save('features_test_%s.nd' % (model_name), features)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 10222/10222 [00:00<00:00, 21065.56it/s]\n"
     ]
    }
   ],
   "source": [
    "df = pd.read_csv('labels.csv')\n",
    "synset = sorted(set(df['breed']))\n",
    "n = len(df)\n",
    "lis_y = []\n",
    "for i, (fname, breed) in tqdm(df.iterrows(), total=n):\n",
    "    lis_y.append(synset.index(breed))\n",
    "    nd.waitall()\n",
    "y = nd.array(lis_y).reshape((n,1))\n",
    "\n",
    "imgs_224_test = vision.ImageFolderDataset('for_test', transform=transform1)\n",
    "imgs_299_test = vision.ImageFolderDataset('for_test', transform=transform2)\n",
    "\n",
    "data_test_iter_224 = gluon.data.DataLoader(gluon.data.ArrayDataset(imgs_224_test), batch_size=128)\n",
    "data_test_iter_299 = gluon.data.DataLoader(gluon.data.ArrayDataset(imgs_299_test), batch_size=128)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 81/81 [01:55<00:00,  1.43s/it]\n"
     ]
    }
   ],
   "source": [
    "model_1 = 'inceptionv3'\n",
    "\n",
    "save_features(model_1, data_test_iter_299)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model_2 = 'resnet152_v1'\n",
    "\n",
    "save_features(model_2, data_test_iter_224)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
